<template>
  <div class="create-post-page">
    <h4>{{route.query.id ? '编辑文章' : '新建文章'}}</h4>
    <Uploader
    action="/upload"
    :boforeUpload="uploadCheck"
    @file-uploaded="fileUploaded"
    :uploaded="uploadedData"
    class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <h4>点击上传头图</h4>
      <template #loading>
          <div class="d-flex">
            <div class="spinner-border text-secondary" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
            <h2>正在上传</h2>
          </div>
      </template>

      <template #uploaded="dataProps">
          <img :src="dataProps.uploadData.data.url" alt="">
      </template>
      
      <template #error>
        <h4>上传失败</h4>
      </template>
      
    </Uploader>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules" v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows="10"
          tag="textarea"
          placeholder="请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">
          {{route.query.id  ? '更新文章' : '发表文章'}}
        </button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
/* 添加自定义上传文件的样式 */
import { defineComponent, ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

import {GlobalDataProps,ResponseType,ImageProps} from '@/store/index'

import ValidateInput,{RuleProps} from '@/components/validateInput/validateInput.vue'
import ValidateForm from '@/components/ValidateForm/ValidateForm.vue'

import Uploader from '@/components/Uploader/Uploader.vue'

import {beforeUploadCheck} from '@/helper/helper'
import createMessage from '@/hooks/createMessage'

import {createPosts,editPost} from '@/api/index'

export default defineComponent({
  name: 'CreatePost',
  components: {
    ValidateInput,
    ValidateForm,
    Uploader
  },
  setup() {
    const uploadedData = ref()
    const titleVal = ref('')
    const router = useRouter()
    const route = useRoute()
    const store = useStore<GlobalDataProps>()
    const imgUrl = ref('')
    // store.commit('setUnAbleCreate',false)
    const titleRules: RuleProps = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contentVal = ref('')
    const contentRules: RuleProps = [
      { type: 'required', message: '文章详情不能为空' }
    ]
    const isEditMode = route.query.id
    onMounted(() => {
      console.log('onMounted......');
      console.log('route.query.id==',route.query.id);
      if (isEditMode) {
        console.log('isEditMode777777==',isEditMode);
        
        editPost(isEditMode.toString()).then(rawData => {
          console.log('成功：',rawData);
          const currentPost = rawData.data.data
          if (currentPost.image){
            uploadedData.value = {data:currentPost.image}
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''

          
        }).catch(err => {
          console.log('失败：',err);
          
        })
      }
      
      
    })
    
    const fileUploaded = (data:ResponseType<ImageProps>) => {
      console.log('上传成功',data.data._id);
      if (data.data._id) {
        imgUrl.value = data.data._id
      }
      console.log('imgUrl==',imgUrl.value);
      
      
    }
   
   const currentId = computed(()=> store.state.currentId)
   console.log('currentId1',currentId);
   const aa = localStorage.getItem('currentID')
   console.log('aa=',aa);
   
   const user = computed(() => store.state.user)
   console.log('user:',user);
   
  const {column,email,nickName,_id} = user.value
    const onFormSubmit = (result: boolean) => {
      console.log('onFormSubmit...',result);

    if (result) {
       console.log('currentId2',currentId.value);
      const param = {
        "title": titleVal.value,
        "content": contentVal.value,
        "image": imgUrl.value,
        "column": currentId.value,
        // "column": '5f3e86d62c56ee13bb83096c',
        // "column": column,
        "author": _id
      }
    /*   createPosts(param).then(res => {
        createMessage('穿件文章成功,2秒钟跳转到文章列表','success')
        setTimeout(()=> {
          router.push({name:'columnDetail',query:{id:currentId.value}})
        },2000)
        
      }).catch(err => {
        createMessage('创建失败','error')
        console.log('创建失败：',err);
        
      }) */
      const actionName = isEditMode ? 'updatapost': 'createPost'
      const actionNameStr = isEditMode ? '编辑': '创建'
      const actionPaload = isEditMode ? {id: isEditMode.toString(),payload: param}: param
      store.dispatch(actionName,actionPaload).then(res => {
        createMessage(`${actionNameStr}成功,2秒钟跳转到文章列表`,'success')
        setTimeout(()=> {
          router.push({name:'columnDetail',query:{id:currentId.value}})
        },2000)
      }).catch(err => {
        createMessage(`${actionNameStr}失败`,'error')
      })
    }
      
    }

    // 定义校验上传图片的函数
    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file,{format: ['image/jpeg','image/png'],size:1})
      const {passed,error} = result
      console.log('错误提示：',error);
      
      if (error === 'format') {
        createMessage('只能上传图片格式jpeg或png','error')
      } 

      if (error === 'size') {
        createMessage('只能上传小于1M的图片','error')
      } 
      return passed

    }
    
    return {
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
      uploadedData,
      route,
      uploadCheck,
      fileUploaded
    }
  }
})
</script>
<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
